# -*- coding: utf-8 -*-
import subprocess
import logging
import json
import os
import time

SUPPORTED_SRC_SUFFIXES = ['.mov']
SUPPORTED_DST_SUFFIXES = ['mp4', "avi"]

class TranscodeError(Exception):
    def __init__(self, message, status):
        super().__init__(message, status)

def run_cmd(cmd_lst):
    try:
        subprocess.check_call(
            cmd_lst, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
    except subprocess.CalledProcessError as e:
        err_log = f'''
        returncode: {e.returncode}
        cmd: {e.cmd}
        output: {e.output}
        stderr: {e.stderr}
        stdout: {e.stdout}
        '''
        logging.error(err_log)
        raise TranscodeError(e.output, e.returncode)

def handler(event, context):
    evt = json.loads(event)
    # split video key, locate in nas
    input_path = evt['filekey']
    dir_path, file_name = os.path.split(input_path)
    file_base_name, file_suffix = os.path.splitext(file_name)
    if file_suffix not in SUPPORTED_SRC_SUFFIXES:
        raise TranscodeError(message='Unsupported file suffix {}'.format(file_suffix))
    target_type = evt['format']
    if target_type not in SUPPORTED_DST_SUFFIXES:
        raise TranscodeError(message='Unsupported target type {}'.format(target_type))
    dst_filename = 'transcoded_%s.%s' % (file_base_name, target_type)
    dst_filepath = os.path.join(dir_path, dst_filename)

    if os.path.exists(dst_filepath):
        os.remove(dst_filepath)

    run_cmd(['/opt/ffmpeg/ffmpeg', '-y', '-i', input_path, dst_filepath])
    return evt
